package com.situ.blog.dao.impl;

import com.situ.blog.dao.IBlogDao;
import com.situ.blog.pojo.Blog;
import com.situ.blog.pojo.query.BlogQuery;
import com.situ.blog.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

public class BlogDaoImpl implements IBlogDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<Blog> list(BlogQuery blogQuery) {
        String sql = "SELECT id,name,image,click_count,content,type_id,status,is_deleted,create_time,update_time FROM blog WHERE 1=1";
        List<Object> queryList = new ArrayList<>();
        String queryName = blogQuery.getName();
        if (queryName != null && !"".equals(queryName)) {
            sql += " AND name LIKE ?";
            queryList.add("%" + queryName + "%");
        }
        Integer typeId = blogQuery.getTypeId();
        if (typeId != null) {
            sql += " AND type_id=?";
            queryList.add(typeId);
        }
        return template.query(sql, new BeanPropertyRowMapper<>(Blog.class), queryList.toArray());
    }

    @Override
    public Blog selectById(int id) {
        String sql = "SELECT id,name,image,click_count,content,type_id,status,is_deleted,create_time,update_time FROM blog WHERE id=?";
        return template.queryForObject(sql, new BeanPropertyRowMapper<>(Blog.class), id);
    }
}
